import {reqTuikuan} from '../../../api/mine'
import {reqUpdorderstatus} from '../../../api/order'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 游客列表
    tourists: [{ checked: false }],
    selectAll: true, // 全选状态
    selectedTourists: [], // 选中的游客ID数组
    refundAmount: 0,     // 自动计算的总退款金额
    totalAmount: 0,      // 所有游玩人的总价（从options获取）
    // 退款原因
    refundReasons: [
      { id: 1, name: '临时不想去了' },
      { id: 2, name: '天气不合适' },
      { id: 3, name: '选错日期' },
      { id: 4, name: '信息不符' },
      { id: 5, name: '其他原因' }
    ],
    selectedReason: {}, // 选中的退款原因
    refundDesc: '', // 退款说明
    
    // 图片上传
    images: [], // 本地临时图片路径
    uploadedImages: [], // 上传到服务器的图片URL
    id: '', //订单id
    orderNo:'',
    tourdate: '',
    totalPeople: 0, // 总游玩人数（订单中的总人数）
    selectedCount: 0, // 当前选中的退款人数
    totalRefundable: 0, // 总价可退金额（扣手续费后）
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    const data = JSON.parse(decodeURIComponent(options.player)); // 游客列表
    const tourdate = options.tourdate;
    const id = options.id;
    const orderNo=options.orderNo;
    const totalAmount = Number(options.totalAmount); // 所有游玩人的总价
    const totalPeople = data.length; // 总游玩人数（核心：从游客列表长度获取）

    // 计算总价可退金额（应用手续费规则）
    const totalRefundable = this.tuikuanprice(tourdate, totalAmount).refundAmount;

    // 默认全选（所有游玩人）
    const tourists = data.map(item => ({
      ...item,
      checked: true // 默认勾选所有游客
    }));

    // 初始总退款 = 总价可退金额（因为默认全选）
    this.setData({
      orderNo,
      tourists: tourists,
      tourdate,
      id,
      totalPeople: totalPeople, // 总游玩人数
      totalAmount: totalAmount, // 所有游玩人的总价
      totalRefundable: totalRefundable, // 总价可退金额
      selectedCount: totalPeople, // 初始选中人数=总人数
      refundAmount: totalRefundable // 初始总退款金额
    });
  },

  /** 
   * 计算总价可退金额（应用手续费规则）
   */
  tuikuanprice(tourdate, totalAmount) {
    // 1. 解析游玩结束时间
    const [dateStr, timeRange] = tourdate.split(' ');
    const [_, endTimeStr] = timeRange.split('-'); // 获取结束时间
    const tourEnd = new Date(`${dateStr}T${endTimeStr}:00`);
    const now = new Date();
    const timeDiff = tourEnd - now;
    const hoursDiff = timeDiff / (1000 * 60 * 60); // 转换为小时

    // 2. 应用手续费规则（24小时内扣30%）
    let refundable;
    if (hoursDiff <= 24 && hoursDiff >= 0) {
      refundable = Math.round(totalAmount * 0.7 * 100) / 100; // 扣30%手续费
    } else {
      refundable = totalAmount; // 24小时外全额退款
    }

    return { refundAmount: refundable };
  },

  /**
   * 全选/取消全选
   */
  toggleSelectAll(e) {
    const newSelectAll = !this.data.selectAll;
    const updatedTourists = this.data.tourists.map(tourist => ({
      ...tourist,
      checked: newSelectAll
    }));
    const selectedCount = newSelectAll ? this.data.totalPeople : 0;
    
    // 计算退款金额：总价可退金额 × (选中人数/总人数)
    const refundAmount = (this.data.totalRefundable * (selectedCount / this.data.totalPeople)).toFixed(2);

    this.setData({
      selectAll: newSelectAll,
      tourists: updatedTourists,
      selectedTourists: newSelectAll ? updatedTourists.map(t => t.id.toString()) : [],
      selectedCount: selectedCount,
      refundAmount: Number(refundAmount)
    });
  },

  /**
   * 游客选择变化事件（核心：动态计算金额）
   */
  onTouristChange(e) {
    const selectedValues = e.detail.value;
    const updatedTourists = this.data.tourists.map(tourist => ({
      ...tourist,
      checked: selectedValues.includes(tourist.id.toString())
    }));
    const selectedCount = selectedValues.length; // 当前选中的退款人数
    
    // 计算退款金额：总价可退金额 × (选中人数/总人数)
    const refundAmount = (this.data.totalRefundable * (selectedCount / this.data.totalPeople)).toFixed(2);

    const isAllSelected = selectedCount === this.data.totalPeople;

    this.setData({
      tourists: updatedTourists,
      selectAll: isAllSelected,
      selectedTourists: selectedValues,
      selectedCount: selectedCount,
      refundAmount: Number(refundAmount)
    });
  },

  /**
   * 退款原因选择变更事件
   */
  reasonChange(e) {
    const index = e.detail.value;
    this.setData({
      selectedReason: this.data.refundReasons[index]
    });
  },

  /**
   * 退款说明输入事件
   */
  inputChange(e) {
    this.setData({
      refundDesc: e.detail.value
    });
  },

  /**
   * 选择图片
   */
  chooseImage() {
    const that = this;
    wx.chooseImage({
      count: 3 - that.data.images.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths)
        that.setData({
          images: that.data.images.concat(tempFilePaths)
        });
        that.uploadImages(tempFilePaths);
      }
    });
  },

  /**
   * 上传图片到服务器
   */
  uploadImages(tempFilePaths) {
    const that = this;
    const uploaded = []; //已经上传了
    
    wx.showLoading({
      title: '上传中...',
      mask: true
    });
    
    // 模拟上传（实际项目替换为真实接口）
    tempFilePaths.forEach((path, index) => {
      setTimeout(() => {
        console.log('上传图片:', path);
       wx.uploadFile({
         url: 'http://127.0.0.1:8024/wx/upload',
         filePath:path,
         name:'file',
        success(res){
           let data=JSON.parse(res.data)
           console.log(data.data.url)
         uploaded.push(data.data.url)
        
        if (uploaded.length === tempFilePaths.length) { //如果所有照片已经上传完成了
          wx.hideLoading();
          that.setData({
            uploadedImages: that.data.uploadedImages.concat(uploaded)
          });
          wx.showToast({ title: '上传成功', icon: 'success' });
        }
      }
    })
      }, 1000 * (index + 1));
    });
  },

  /**
   * 删除图片
   */
  removeImage(e) {
    const index = e.currentTarget.dataset.index;
    const images = [...this.data.images];
    images.splice(index, 1);
    
    const uploadedImages = [...this.data.uploadedImages];
    if (uploadedImages.length > index) {
      uploadedImages.splice(index, 1);
    }
    
    this.setData({ images, uploadedImages });
  },

  /**
   * 提交退款申请（验证最少选1人）
   */
  submitApply() {
    // 1. 验证选中人数（最少1人）
    if (this.data.selectedCount === 0) {
      return wx.showToast({ title: '至少选择1位游客', icon: 'none' });
    }

    // 2. 验证其他必填项
    const { selectedReason, refundDesc } = this.data;
    if (!selectedReason.id) {
      return wx.showToast({ title: '请选择退款原因', icon: 'none' });
    }
    if (!refundDesc.trim()) {
      return wx.showToast({ title: '请输入退款说明', icon: 'none' });
    }

    // 3. 构造提交数据
    const submitData = {
      refundAmount: this.data.refundAmount,
      reasonText: selectedReason.name,
      description: refundDesc,
      imageUrls: this.data.uploadedImages.length > 0 ? this.data.uploadedImages.join(',')  : null,
      orderId:this.data.orderNo
    };
    
    console.log('提交退款申请数据:', submitData);
    //新增了还要改状态为4
    
    // 4. 模拟提交
    wx.showLoading({ title: '提交中...', mask: true });
      reqTuikuan(submitData)
      .then(response => {
          console.log(response)
          if(response=='success'){
         reqUpdorderstatus(this.data.id)
          }
      })
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 2000,
        success: () => setTimeout(()=>{
          wx.navigateTo({
            url: '/pages/mine/payment/payment?tabid=4',
          })
        },2000)
      });
    }, 1500);
  }


});


